<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    width="75%"
    height="70%"
    :close-on-click-modal="false"
    :visible.sync="visible"
  >

    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="80px"
    >
      <el-form-item label="文章标题" prop="articleTitle">
        <el-input
          v-model="dataForm.articleTitle"
          placeholder="文章标题"
        ></el-input>
      </el-form-item>

      <el-form-item label="文章封面" prop="articleHover">
        <div class="avatar-container">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:8888/api/minio/upload"
            :show-file-list="false"
            :on-preview="handlePictureCardPreview"
            :on-success="handleUploadSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img style="width: 150px;height: 150px"  v-if="dataForm.articleHover" :src="dataForm.articleHover" class="avatar" alt="">
            <el-button v-else size="small" type="primary">点击上传</el-button>
          </el-upload>
        </div>
      </el-form-item>


      <el-form-item label="文章内容" prop="articleContent">
        <div >
          <div  style="width: 100%;">
            <quill-editor v-model="dataForm.articleContent" style="height: 250px"></quill-editor>
          </div>
        </div>
      </el-form-item>

      <el-form-item style="margin-top: 100px" label="文章描述" prop="articleDescription">
        <el-input
          v-model="dataForm.articleDescription"
          placeholder="文章描述"
        ></el-input>
      </el-form-item>



      <el-form-item label="文章类型" prop="articleTypeName" style="margin-top: 50px">
        <el-select v-model="dataForm.articleTypeName" placeholder="请选择">
          <el-option
            v-for="item in typeOption"
            :key="item.id"
            :label="item.articleTypeName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="发布讲师" prop="teacherName">
        <el-select v-model="dataForm.teacherName" placeholder="请选择">
          <el-option
            v-for="item in teacherOption"
            :key="item.id"
            :label="item.teacherName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>


    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { quillEditor } from 'vue-quill-editor';
import 'quill/dist/quill.core.css'; // import styles
import 'quill/dist/quill.snow.css'; // for snow theme
import 'quill/dist/quill.bubble.css'; // for bubble theme

export default {
  components: {
    quillEditor
  },
  data () {
    return {
      visible: false,
      dataForm: {
        id: 0,
        articleTitle: '',
        articleContent: '',
        teacherName: '',
        createTime: '',
        updateTime: '',
        articleTypeName: '',
        articleHover: '',
        isDelete: ''
      },
      dialogImageUrl: '',
      dialogVisible: false,
      fileList: [
        {
          name: '',
          url: ''
        }
      ],
      imageUrl: '',
      flag: true,
      typeOption: [],
      teacherOption: [],
      dataRule: {
        articleTitle: [
          { required: true, message: '文章标题不能为空', trigger: 'blur' }
        ],
        articleContent: [
          { required: true, message: '文章内容不能为空', trigger: 'blur' }
        ],
        articleTypeName: [
          { required: true, message: '文章内容不能为空', trigger: 'blur' }
        ],
        articleDescription: [
          { required: true, message: '文章内容不能为空', trigger: 'blur' }
        ],
        teacherName: [
          { required: true, message: '讲师id不能为空', trigger: 'blur' }
        ],
        createTime: [
          { required: false, message: '创建时间不能为空', trigger: 'blur' }
        ],
        updateTime: [
          { required: false, message: '更新时间不能为空', trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    init (id) {
      this.getArticleType()
      this.getTeacherList()
      this.dataForm.id = id || 0;
      this.visible = true;
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields();
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(
              `/article/article/info/${this.dataForm.id}`
            ),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.dataForm.articleTitle = data.article.articleTitle;
              this.dataForm.articleContent = data.article.articleContent;
              this.dataForm.teacherName = data.article.teacherName;
              this.dataForm.articleHover = data.article.articleHover;
              this.dataForm.articleDescription = data.article.articleDescription;
              this.dataForm.articleTypeName = data.article.typeName;
              this.dataForm.createTime = data.article.createTime;
              this.dataForm.updateTime = data.article.updateTime;
              this.dataForm.isDelete = data.article.isDelete;
            }
          });
        }
      });
    },
    // 表单提交
    dataFormSubmit () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.setArticle()
          this.setTeacherlId()
          this.$http({
            url: this.$http.adornUrl(
              `/article/article/${!this.dataForm.id ? 'save' : 'update'}`
            ),
            method: 'post',
            data: this.$http.adornData({
              id: this.dataForm.id || undefined,
              articleTitle: this.dataForm.articleTitle,
              articleContent: this.dataForm.articleContent,
              teacherName: this.dataForm.teacherName,
              articleHover: this.dataForm.articleHover,
              typeName: this.dataForm.articleTypeName,
              articleDescription: this.dataForm.articleDescription,
              createTime: this.dataForm.createTime,
              updateTime: this.dataForm.updateTime,
              isDelete: this.dataForm.isDelete
            })
          }).then(({ data }) => {
            if (data && data.code === 200) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit('refreshDataList');
                }
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    },

    // 获取学生学历等级数据
    getArticleType () {
      this.$http({
        url: this.$http.adornUrl(
          '/article/articletype/findArticleTypeList'
        ),
        method: 'get'
      }).then(({ data }) => {
        if (data && data.code === 0) {
          console.log(data.articleTypeList, 'sadsad');
          this.typeOption = data.articleTypeList;
        } else {
          this.typeOption = [];
        }
      });
    },
    // 打开编辑框的时候为等级设置对应的id
    setArticle () {
      if (typeof this.dataForm.articleTypeName === 'string') {
        for (var i = 0; i < this.options.length; i++) {
          if (
            this.dataForm.id &&
            this.dataForm.articleTypeName === this.typeOption[i].articleTypeName
          ) {
            this.dataForm.articleTypeName = this.typeOption[i].id;
          }
          console.log(this.dataForm.articleTypeName, 'sadas');
        }
      }
    },

    // 获取讲师下拉框
    getTeacherList () {
      this.$http({
        url: this.$http.adornUrl(
          '/teacher/teacher/findTeacherList'
        ),
        method: 'get'
      }).then(({ data }) => {
        if (data && data.code === 0) {
          console.log(data.teacherList);
          this.teacherOption = data.teacherList;
        } else {
          this.teacherOption = [];
        }
      });
    },

    setTeacherlId () {
      if (typeof this.dataForm.teacherName === 'string') {
        for (var i = 0; i < this.teacherOption.length; i++) {
          if (
            this.dataForm.id &&
            this.dataForm.teacherName === this.teacherOption[i].teacherName
          ) {
            this.dataForm.teacherName = this.teacherOption[i].id;
          }
          console.log(this.dataForm.teacherName, 'sadas');
        }
      }
    },
    handlePreview (file) {
      console.log(file);
    },

    handleRemove (file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview (file) {
      console.log(file);
      this.dataForm.articleHover = file.url;
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleUploadSuccess (res, file) {
      console.log(res, 'res')
      console.log(file, 'file')
      this.dataForm.articleHover = res.msg

      // this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload (file) {
      console.log(file.type, 'file')
      const isJPG = file.type === 'image/jpeg';
      const isPng = file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isPng) {
        this.$message.error('上传头像图片只能是 JPG或PNG格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return (isJPG || isPng) && isLt2M;
    },
    updateFlag () {
      this.flag = this.dataForm.articleHover !== '';
      console.log(this.flag);
    },
    close () {
      this.visible = false;
      this.handleRemove(this.fileList);
    }
  }
};
</script>



